const jwt = require("jsonwebtoken")
const sqlMap = require('./sqlMap');
const db = require('./db');

// err为null 说明连接成功
db.connect(err => {console.log('connect',err)});

//加密时候混淆
const secret = '113Bmongojsdalkfnxcvmas'
module.exports = {
  //生成token
  //info也就是payload是需要存入token的信息
  createToken(info) {
    let token = jwt.sign(info, secret, {
          //Token有效时间 单位s
      expiresIn:60 * 60 * 10
    })
    return token
  },

  //验证Token
  verifyToken(token) {
    return new Promise((resolve, reject) => {
      jwt.verify(token, secret, (error, result) => {
        if(error){
            reject(error)
        } else {
            resolve(result)
        }
      })
    })
  },

  // 登录
  login(req, res, next) {
    const userName = req.query.userName;
    const password = req.query.password;
    const user = {
      name: userName,
      pass:password
    }
    // 查询数据库
    const sql = sqlMap.login;
    db.query(sql,[userName, password], (error, result) => {
      if (error) throw error;
      let response = {};
      if(result.length > 0) {
        let token = this.createToken(user)
        response.code = 200;
        response.msg = '登录成功'
        response.token = token;
        res.json(response)
      } else {
        response.code = 500;
        response.msg = '登录失败,账号或密码错误'
        res.json(response)
      }
    })
  },

  // 注册
  register(req, res, next) {
    const userName = req.body.userName;
    const password = req.body.password;
    const sql = sqlMap.selectUser;
    let response = {};
    // 判断用户名是否存在
    db.query(sql,[userName], (error, result) => {
      if (error) throw error;
      console.log('该用户已存在', result);
      if(result.length > 0) {
        response.code = 500;
        response.msg = '注册失败,用户名已存在!'
        res.json(response);
      } else {
        // 不存在则添加用户
        const sql = sqlMap.registerUser;
        db.query(sql,[userName, password], (err, result) => {
          if(err) {
            console.log('INSERT ERR',err)
            return
          } else {
            console.log('INSERT DATA:',result)
            response.code = 200;
            response.msg = '注册成功'
            res.json(response);
          }
        })
      }
    })
  }
}
;


